package com.jadefashion.service.impl;

import com.jadefashion.mapper.OrderSettingMapper;
import com.jadefashion.pojo.OrderSetting;
import com.jadefashion.service.OrderSettingService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(timeout =5000 )
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    OrderSettingMapper orderSettingMapper;

    //根据日期设置预约数
    @Override
    public void update(Integer number, String date) {
        orderSettingMapper.updateNumberByDate(number,date);
    }

    @Override
    public void cleanOrderSetting(String lastDay) {
        orderSettingMapper.cleanOrderSetting(lastDay);
    }

    @Override
    public List<Map<String, Object>> findDate(Integer year, Integer month, Integer day) {
        Calendar calendar = Calendar.getInstance();
       //如果年份月份相同，则从当天的第二天查询
        if(year==calendar.get(Calendar.YEAR)&&(month-1==calendar.get(Calendar.MONTH))){
            calendar.add(Calendar.DAY_OF_MONTH,1);
        }else {//如果年分或者月份不相同，则从选择的月份1号开始查询。
            calendar.set(Calendar.MONTH,month-1);
            calendar.set(Calendar.YEAR,year);
            calendar.set(Calendar.DAY_OF_MONTH,1);
        }
        String begin=calendar.get(calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+calendar.get(Calendar.DAY_OF_MONTH);
        String end=calendar.get(calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-31";
        List<Map<String, Object>> map=new ArrayList<>();
        List<OrderSetting> orderSettingList=orderSettingMapper.findDate(begin,end);
        for (OrderSetting orderSetting : orderSettingList) {
            Date orderDate = orderSetting.getOrderDate();
            calendar.setTime(orderDate);
            int date = calendar.get(Calendar.DAY_OF_MONTH);
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("date",date);
            hashMap.put("number",orderSetting.getNumber());
            hashMap.put("reservations",orderSetting.getReservations());
            hashMap.put("currentYear",calendar.get(Calendar.YEAR));
            hashMap.put("currentMonth",calendar.get((Calendar.MONTH)));
            map.add(hashMap);
        }
        return map;
    }

    @Override
    public void add(List<OrderSetting> orderSettingListList) {
        for (OrderSetting orderSetting : orderSettingListList) {
            Date orderDate = orderSetting.getOrderDate();
            Long count=orderSettingMapper.findCountByDate(orderDate);
            if(count>0){//有值则覆盖，无值则添加
                orderSettingMapper.updateByDate(orderSetting);
            }else {
                orderSettingMapper.add(orderSetting);
            }
        }
    }
}
